/*
    kOTF Open Trace Format - a library for generating execution traces.
    Copyright 2012 Daniel K. O.

    kOTF is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    kOTF is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with kOTF.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef KOTF_WRITER_H
#define KOTF_WRITER_H

#include <queue>

#include <kotf/Events.hpp>

#include "TypesInternal.hpp"

namespace kotf {

    class SessionImpl;
    class StreamImpl;
    class EventBuffer;

    class Writer {

        class ParallelQueue {
            std::queue< EventBuffer* > data;
            mutable mutex dataMutex;
            condition_variable emptyCondition;
        public:
            void push(EventBuffer* eb);
            EventBuffer* pop();
            EventBuffer* try_pop();
            bool empty() const;
            size_t size() const;
        };

        ParallelQueue pending;
        ParallelQueue available;
        
        thread worker;
        void pushTermination(); // pushes a null event buffer

        Writer();
        friend class SessionImpl;

    public:
        ~Writer();

        void pushPending(EventBuffer* eb);
        
        EventBuffer* popPending();

        void recycle(EventBuffer *eb);

        EventBuffer* getAvailable(StreamImpl* stream);

        void start(); // starts the worker thread

        void stop(); // stops the worker thread

    };

}


#endif
